package com.example.verifysdk;

import android.app.Activity;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.media.ExifInterface;
import android.media.FaceDetector;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.text.TextUtils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * @author liuv
 */
public class UploadHelper {
    private static final String TAG = "UploadHelper";

    private static final String CAMERA_IMAGE_NAME = "_header";

    public static final int REQUEST_CODE_TAKE_PICTURE = 1;
    public static final int REQUEST_CODE_SELECT_ALBUM = 2;
    //        public static final String SERVICE_URL = "http://192.168.0.9:1080/skynet";
//        public static final String SERVICE_URL = "http://192.168.0.124/skynet";
//        public static final String SERVICE_URL = "http://192.168.0.69/skynet";
//    private static final String SERVICE_URL = "https://xingtai.video110.cn:8000/skynet/";
        public static final String SERVICE_URL = "https://www.video110.cn:8000/skynet/";
    private static final String UPLOAD_IMG_URL = "api/partner/uploadFile";
    private static final MediaType MEDIA_TYPE_JPG = MediaType.parse("image/jpg");

    public static String getUrl(Context context){
        String host = new SpHelper(context).getServiceHost();
        LogUtil.i(TAG, "---getUrl===" + host);
        if (TextUtils.isEmpty(host)){
            return SERVICE_URL;
        }else {
            return host;
        }
    }

    public static void selectImageFromStore(Activity context, int requestCode) {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("image/*");
        context.startActivityForResult(intent, requestCode);
    }

    public static void selectImageFromCamer(Activity context, int requestCode,
                                            File saveImage) {
        if (saveImage == null) {
            LogUtil.i(TAG, "Image file parameter is null.");
            return;
        }
        int currentapiVersion = android.os.Build.VERSION.SDK_INT;
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (currentapiVersion < 24) {
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(saveImage));
            intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
        } else {
            ContentValues contentValues = new ContentValues();
            contentValues.put(MediaStore.Images.Media.DATA, saveImage.getAbsolutePath());
            Uri uri = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,contentValues);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        }
        context.startActivityForResult(intent, requestCode);
    }

    /**
     * 获取存储拍照图片的文件
     *
     * @param context
     * @return
     */
    public static File getCameraSaveFile(Context context, long phoneName) {
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            return new File(Environment.getExternalStorageDirectory(),
                    phoneName + CAMERA_IMAGE_NAME + ".jpg");
        } else {
            return null;
        }
    }

    public static void startPhotoZoom(Activity context, Uri uri, int outX,
                                      int outY, int requestCode) {
        if (uri == null) {
            LogUtil.i(TAG, "The uri is not exist.");
            return;
        }

        Intent intent = new Intent("com.android.camera.action.CROP");
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
            String path = getImageAbsolutePath(context, uri);
            intent.setDataAndType(Uri.fromFile(new File(path)), "image/*");
        } else {
            intent.setDataAndType(uri, "image/*");
        }

        // 设置裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 200);
        intent.putExtra("outputY", 200);
        intent.putExtra("return-data", true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        context.startActivityForResult(intent, requestCode);
    }


    /**
     * 根据Uri获取图片绝对路径，解决Android4.4以上版本Uri转换
     */
    public static String getImageAbsolutePath(Context context, Uri imageUri) {
        if (context == null || imageUri == null) {
            return null;
        }

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT
                && DocumentsContract.isDocumentUri(context, imageUri)) {
            if (isExternalStorageDocument(imageUri)) {
                String docId = DocumentsContract.getDocumentId(imageUri);
                String[] split = docId.split(":");
                String type = split[0];
                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/"
                            + split[1];
                }
            } else if (isDownloadsDocument(imageUri)) {
                String id = DocumentsContract.getDocumentId(imageUri);
                Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"),
                        Long.valueOf(id));
                return getDataColumn(context, contentUri, null, null);
            } else if (isMediaDocument(imageUri)) {
                String docId = DocumentsContract.getDocumentId(imageUri);
                String[] split = docId.split(":");
                String type = split[0];
                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }
                String selection = MediaStore.Images.Media._ID + "=?";
                String[] selectionArgs = new String[]{split[1]};
                return getDataColumn(context, contentUri, selection,
                        selectionArgs);
            }
        } // MediaStore (and general)
        else if ("content".equalsIgnoreCase(imageUri.getScheme())) {
            // Return the remote address
            if (isGooglePhotosUri(imageUri)) {
                return imageUri.getLastPathSegment();
            }
            return getDataColumn(context, imageUri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(imageUri.getScheme())) {
            return imageUri.getPath();
        }
        return null;
    }

    public static BitmapFactory.Options compressImage(String imgPath) {
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        newOpts.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeFile(imgPath, newOpts);
        newOpts.inJustDecodeBounds = false;
        int oldWidth = newOpts.outWidth;
        int oldHeight = newOpts.outHeight;
        if (newOpts.outHeight > newOpts.outWidth) {
            oldWidth = newOpts.outHeight;
            oldHeight = newOpts.outWidth;
        }
        int inSampleSize = 2;
        if (oldWidth > 1000 || oldHeight > 1000) {
            inSampleSize = 4;
        }
        newOpts.inSampleSize = inSampleSize;
        newOpts.inPreferredConfig = Bitmap.Config.RGB_565;
        return newOpts;
    }

    /** 修剪图片 */
    public static void clipImage(final String imgPath){
        Bitmap bitmap = BitmapFactory.decodeFile(imgPath);
        if (bitmap == null){
            return;
        }
        LogUtil.i(TAG, "---clipImage=getHeight==" + bitmap.getHeight());
        LogUtil.i(TAG, "---clipImage=getWidth==" + bitmap.getWidth());
        double scale = bitmap.getHeight() / (double)(bitmap.getWidth());
        LogUtil.i(TAG, "---clipImage=scale==" + scale);
        if (scale < 1){
            int w = (int) (bitmap.getHeight() * scale);
            int x = (bitmap.getWidth() / 2) - (w / 2);
            LogUtil.i(TAG, "---clipImage=w==" + w);
            Bitmap cutBitmap = Bitmap.createBitmap(
                    bitmap,
                    x,
                    0,
                    w,
                    bitmap.getHeight()
            );
            LogUtil.i(TAG, "---clipImage=cutBitmap.getHeight==" + cutBitmap.getHeight());
            LogUtil.i(TAG, "---clipImage=cutBitmap.getWidth==" + cutBitmap.getWidth());
            FileOutputStream stream = null;
            try {
                stream = new FileOutputStream(imgPath);
                cutBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
                stream.flush();
                stream.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                cutBitmap.recycle();
                bitmap.recycle();
            }
        }
    }

    //图片旋转至正向
    public static Bitmap rotateBitmap(int whichImg, String imgPath, Bitmap bitmap){
        int digree = 0;
        ExifInterface exif = null;
        try {
            exif = new ExifInterface(imgPath);
        } catch (IOException e) {
            e.printStackTrace();
            exif = null;
        }
        if (exif != null) {
            // 读取图片中相机方向信息
            int ori = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_UNDEFINED);
            // 计算旋转角度
            switch (ori) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    digree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    digree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    digree = 270;
                    break;
                default:
                    digree = 0;
                    break;
            }
        }
        if (digree != 0) {
            // 旋转图片
            Matrix m = new Matrix();
            m.postRotate(digree);
            bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
                    bitmap.getHeight(), m, true);
        }
        if (whichImg == 1){
            try {
                FileOutputStream stream = new FileOutputStream(imgPath);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
                stream.flush();
                stream.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return bitmap;
    }

    /**
     * 从给定路径加载图片
     */
    public static Bitmap loadBitmap(String imgpath) {
        return BitmapFactory.decodeFile(imgpath);
    }

    /**
     * 从给定的路径加载图片，并指定是否自动旋转方向
     */
    private static Bitmap loadBitmap(String imgpath, boolean adjustOritation) {
        if (!adjustOritation) {
            return loadBitmap(imgpath);
        } else {
            Bitmap bm = loadBitmap(imgpath);
            int digree = 0;
            ExifInterface exif = null;
            try {
                exif = new ExifInterface(imgpath);
            } catch (IOException e) {
                e.printStackTrace();
                exif = null;
            }
            if (exif != null) {
                // 读取图片中相机方向信息
                int ori = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                        ExifInterface.ORIENTATION_UNDEFINED);
                // 计算旋转角度
                switch (ori) {
                    case ExifInterface.ORIENTATION_ROTATE_90:
                        digree = 90;
                        break;
                    case ExifInterface.ORIENTATION_ROTATE_180:
                        digree = 180;
                        break;
                    case ExifInterface.ORIENTATION_ROTATE_270:
                        digree = 270;
                        break;
                    default:
                        digree = 0;
                        break;
                }
            }
            if (digree != 0) {
                // 旋转图片
                Matrix m = new Matrix();
                m.postRotate(digree);
                Bitmap rotatedBitmap = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(),
                        bm.getHeight(), m, false);
                if (bm != rotatedBitmap) {
                    // 有时候 createBitmap会复用对象
                    bm.recycle();
                }
                bm = rotatedBitmap;
            }else {
                if (bm != null){
                    bm.recycle();
                }
                return null;
            }
            return bm;
        }
    }

    /** 旋转图片到正向 */
    public static void rotateImage(final String imgPath){
        Bitmap bitmap = loadBitmap(imgPath, true);
        if (bitmap == null){
            LogUtil.i(TAG, "---bitmap===null==");
            System.gc();
            return;
        }
        try {
            File f = new File(imgPath);
            if (f.exists()){
                f.delete();
            }
            FileOutputStream fos = new FileOutputStream(f);
            f.createNewFile();
            // 把Bitmap对象解析成流
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            bitmap.recycle();
        }
        System.gc();

    }

    /** 旋转图片到正向并裁剪成竖向照片 */
    public static void rotateAndCutImage(final String imgPath){
        LogUtil.i(TAG, "---rotateAndCutImage===" + imgPath);

        Bitmap bitmap = loadBitmap(imgPath, true);
        LogUtil.i(TAG, "---rotateAndCutImage=bitmap.getWidth==" + bitmap.getWidth());
        LogUtil.i(TAG, "---rotateAndCutImage=bitmap.getHeight==" + bitmap.getHeight());

        Bitmap cutBitmap = null;
        if (bitmap == null){
            LogUtil.i(TAG, "---rotateAndCutImage=bitmap==null==");
            System.gc();
            return;
        }
        double scale = bitmap.getHeight() / (double)(bitmap.getWidth());
        LogUtil.i(TAG, "---clipImage=scale==" + scale);
        if (scale < 1) {
            int w = (int) (bitmap.getHeight() * scale);
            int x = (bitmap.getWidth() / 2) - (w / 2);
            LogUtil.i(TAG, "---clipImage=w==" + w);
            cutBitmap = Bitmap.createBitmap(
                    bitmap,
                    x,
                    0,
                    w,
                    bitmap.getHeight()
            );
            LogUtil.i(TAG, "---clipImage=cutBitmap.getHeight==" + cutBitmap.getHeight());
            LogUtil.i(TAG, "---clipImage=cutBitmap.getWidth==" + cutBitmap.getWidth());
        }
        try {
            File f = new File(imgPath);
            if (f.exists()){
                f.delete();
            }
            FileOutputStream fos = new FileOutputStream(f);
            f.createNewFile();
            // 把Bitmap对象解析成流
            if (cutBitmap == null) {
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            }else {
                cutBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            }
            fos.flush();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            bitmap.recycle();
            if (cutBitmap != null){
                cutBitmap.recycle();
            }
        }
        System.gc();

    }

    public static Bitmap compressBitmap(Bitmap image, int maxSize) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 90;
        while (baos.toByteArray().length > maxSize * 1024) { // 循环判断如果压缩后图片是否大于maxSize kb,大于继续压缩
            LogUtil.i(TAG, "---compressBitmap===" + (baos.toByteArray().length / 1024));
            baos.reset(); // 重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
            options -= 10;// 每次都减少10
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
        return bitmap;
    }

    /** 缩放图片使之边长最长不超过1024 */
    public static Bitmap decodeZoomBitmap(String imgPath){
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
//        options.inPreferredConfig = Bitmap.Config.RGB_565;
        BitmapFactory.decodeFile(imgPath, options);
        int w = options.outWidth;
        int h = options.outHeight;
        int n = 1024;
        int s = w >= h ? w / n : h / n;
        options.inSampleSize = s;
        LogUtil.i(TAG, "---decodeZoomBitmap===s=" + s);
        LogUtil.i(TAG, "---decodeZoomBitmap===w=" + w);
        LogUtil.i(TAG, "---decodeZoomBitmap===h=" + h);
        options.inJustDecodeBounds = false;
        Bitmap bitmap = BitmapFactory.decodeFile(imgPath, options);
        //把横的两边切掉变成竖的
        if (bitmap.getHeight() < bitmap.getWidth()) {
            LogUtil.i(TAG, "---decodeZoomBitmap===bitmap.getHeight()=" + bitmap.getHeight());
            LogUtil.i(TAG, "---decodeZoomBitmap===bitmap.getWidth()=" + bitmap.getWidth());
            double scale = bitmap.getHeight() / (double) (bitmap.getWidth());
            int width = (int) (bitmap.getHeight() * scale);
            int x = (bitmap.getWidth() / 2) - (width / 2);
            bitmap = Bitmap.createBitmap(
                    bitmap,
                    x,
                    0,
                    width,
                    bitmap.getHeight()
            );
        }
        return bitmap;
    }

    /** 压缩图片文件的质量到指定大小 */
    public static void compressImageFile(final String imgPath, final int maxSize, final Handler handler){
        new Thread(new Runnable() {
            @Override
            public void run() {
                rotateImage(imgPath);
                Bitmap bitmap = decodeZoomBitmap(imgPath);
                int msgCode = 1;
                if (bitmap == null){
                    LogUtil.i(TAG, "---bitmap===null===" + imgPath);
                    System.gc();
                    handler.sendEmptyMessage(msgCode);
                    return;
                }
                try {
                    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                    LogUtil.i(TAG, "---compressImageFile=baos.length==" + baos.toByteArray().length);
                    int options = 90;
                    while (baos.toByteArray().length > maxSize * 1024) {    //图片的大小不超过maxSize(Kb)
                        LogUtil.i(TAG, "---compressBitmap===" + (baos.toByteArray().length / 1024));
                        baos.reset();
                        bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);
                        options -= 10;
                    }

                    Bitmap tempBitmap = BitmapFactory.decodeByteArray(baos.toByteArray(), 0, baos.size());
                    LogUtil.i(TAG, "---compressImageFile=newBm.getHeight==" + tempBitmap.getHeight());
                    LogUtil.i(TAG, "---compressImageFile=newBm.getWidth==" + tempBitmap.getWidth());
                    LogUtil.i(TAG, "---compressImageFile=newBm.getByteCount==" + tempBitmap.getByteCount());
                    LogUtil.i(TAG, "---compressImageFile=options==" + options);
                    LogUtil.i(TAG, "---bitmapFaceDetector=baos==" + baos.size());

                    //查找人脸
//                    if (baos.size() > 0){
//                        final ByteArrayOutputStream tempBaos = baos;
//                        new Thread(new Runnable() {
//                            @Override
//                            public void run() {
//                                Bitmap faceBitmap = BitmapFactory.decodeByteArray(tempBaos.toByteArray(),
//                                        0,
//                                        tempBaos.size()).copy(Bitmap.Config.RGB_565, true);
//                                FaceDetector faceDetector = new FaceDetector(faceBitmap.getWidth(), faceBitmap.getHeight(), 1);
//                                FaceDetector.Face[] faces = new FaceDetector.Face[1];
//                                faceDetector.findFaces(faceBitmap, faces);
//                                if (faces[0] != null) {
//                                    LogUtil.i(TAG, "---bitmapFaceDetector=confidence==" + faces[0].confidence());
//                                    LogUtil.i(TAG, "---bitmapFaceDetector=eyesDistance==" + faces[0].eyesDistance());
//                                    PointF pointF = new PointF();
//                                    faces[0].getMidPoint(pointF);
//                                    LogUtil.i(TAG, "---bitmapFaceDetector=PointF==" + pointF.toString());
//                                }
//                                faceDetector = null;
//                                faceBitmap.recycle();
//
//                                if (faces[0] != null && faces[0].confidence() > 0.3){
//                                    //图里有人脸
//                                    handler.sendEmptyMessage(3);
//                                }else {
//                                    //图里没人脸
//                                    handler.sendEmptyMessage(4);
//                                }
//                            }
//                        }).start();
//                        tempBaos.close();
//                    }

                    File f = new File(imgPath);
                    LogUtil.i(TAG, "---compressImageFile=1==" + f.length());
                    if (f.exists()){
                        f.delete();
                        f.createNewFile();
                    }
                    LogUtil.i(TAG, "---compressImageFile=2==" + f.length());
                    FileOutputStream fileOutputStream = new FileOutputStream(f);
                    fileOutputStream.write(baos.toByteArray());
                    LogUtil.i(TAG, "---compressImageFile=3==" + f.length());
                    baos.close();
                    fileOutputStream.flush();
                    fileOutputStream.close();
                    tempBitmap.recycle();
                } catch (IOException e) {
                    e.printStackTrace();
                }finally {
                    bitmap.recycle();
                    System.gc();
                    msgCode = 2;
                }
                Message msg = new Message();
                msg.what = msgCode;
                msg.obj = imgPath;
                handler.sendMessage(msg);

//                boolean hasFace = bitmapFaceDetector(imgPath);
//                handler.sendEmptyMessage(hasFace ? 3 : 4);
            }
        }).start();
    }

    /** 检查图片文件中是否有人脸 */
    public static boolean bitmapFaceDetector(String imgPath){
        Bitmap bitmap = BitmapFactory.decodeFile(imgPath);
        LogUtil.i(TAG, "---bitmapFaceDetector===" + imgPath);
        if (bitmap == null){
            return false;
        }
        Bitmap faceBitmap = bitmap.copy(Bitmap.Config.RGB_565, true);
        FaceDetector faceDetector = new FaceDetector(faceBitmap.getWidth(), faceBitmap.getHeight(), 1);
        FaceDetector.Face[] faces = new FaceDetector.Face[1];
        faceDetector.findFaces(faceBitmap, faces);
        if (faces[0] != null) {
            LogUtil.i(TAG, "---bitmapFaceDetector=confidence==" + faces[0].confidence());
            LogUtil.i(TAG, "---bitmapFaceDetector=eyesDistance==" + faces[0].eyesDistance());
            PointF pointF = new PointF();
            faces[0].getMidPoint(pointF);
            LogUtil.i(TAG, "---bitmapFaceDetector=PointF==" + pointF.toString());
        }
        faceDetector = null;
        faceBitmap.recycle();
        bitmap.recycle();
        System.gc();
        return faces[0] != null && faces[0].confidence() > 0.3;
    }

    /**
     * 图片的缩放方法
     *
     * @param bitmap  ：源图片资源
     * @param maxSize ：图片允许最大空间  单位:KB
     * @return
     */
    public static Bitmap getZoomImage(Bitmap bitmap, double maxSize) {
        if (null == bitmap) {
            return null;
        }
        if (bitmap.isRecycled()) {
            return null;
        }

        // 单位：从 Byte 换算成 KB
        double currentSize = bitmapToByteArray(bitmap, false).length / 1024;
        // 判断bitmap占用空间是否大于允许最大空间,如果大于则压缩,小于则不压缩
        while (currentSize > maxSize) {
            // 计算bitmap的大小是maxSize的多少倍
            double multiple = currentSize / maxSize;
            // 开始压缩：将宽带和高度压缩掉对应的平方根倍
            // 1.保持新的宽度和高度，与bitmap原来的宽高比率一致
            // 2.压缩后达到了最大大小对应的新bitmap，显示效果最好
            bitmap = getZoomImage(bitmap, bitmap.getWidth() / Math.sqrt(multiple), bitmap.getHeight() / Math.sqrt(multiple));
            currentSize = bitmapToByteArray(bitmap, false).length / 1024;
        }
        return bitmap;
    }

    /**
     * 图片的缩放方法
     *
     * @param orgBitmap ：源图片资源
     * @param newWidth  ：缩放后宽度
     * @param newHeight ：缩放后高度
     * @return
     */
    public static Bitmap getZoomImage(Bitmap orgBitmap, double newWidth, double newHeight) {
        if (null == orgBitmap) {
            return null;
        }
        if (orgBitmap.isRecycled()) {
            return null;
        }
        if (newWidth <= 0 || newHeight <= 0) {
            return null;
        }

        // 获取图片的宽和高
        float width = orgBitmap.getWidth();
        float height = orgBitmap.getHeight();
        // 创建操作图片的matrix对象
        Matrix matrix = new Matrix();
        // 计算宽高缩放率
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        // 缩放图片动作
        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap bitmap = Bitmap.createBitmap(orgBitmap, 0, 0, (int) width, (int) height, matrix, true);
        return bitmap;
    }

    /**
     * bitmap转换成byte数组
     *
     * @param bitmap
     * @param needRecycle
     * @return
     */
    public static byte[] bitmapToByteArray(Bitmap bitmap, boolean needRecycle) {
        if (null == bitmap) {
            return null;
        }
        if (bitmap.isRecycled()) {
            return null;
        }

        ByteArrayOutputStream output = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, output);
        if (needRecycle) {
            bitmap.recycle();
        }

        byte[] result = output.toByteArray();
        try {
            output.close();
        } catch (Exception e) {
            LogUtil.e(TAG, e.toString());
        }
        return result;
    }

    public static void uploadAllImage(String pId, String userId, Map<File, String> imgFileMap, Context context, Callback callback) {
        if (imgFileMap.size() == 0) {
            return;
        }
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        for (Map.Entry<File, String> entry : imgFileMap.entrySet()) {
            builder.addFormDataPart("img_" + entry.getValue(), entry.getKey().getName(), RequestBody.create(MEDIA_TYPE_JPG, entry.getKey()));
        }

        MultipartBody body = builder
                .addFormDataPart("partnerId", pId)
                .addFormDataPart("partnerRemark", userId)
                .build();

        Request request = new Request.Builder()
                .url(getUrl(context) + UPLOAD_IMG_URL)
                .post(body)
                .addHeader("APP_TOKEN", new SpHelper(context).getString(SpHelper.SDK_TOKEN))
                .build();
        new OkHttpClient
                .Builder()
                .readTimeout(90, TimeUnit.SECONDS)
                .build()
                .newCall(request)
                .enqueue(callback);
    }


    private static String getDataColumn(Context context, Uri uri,
                                        String selection, String[] selectionArgs) {
        Cursor cursor = null;
        String column = MediaStore.Images.Media.DATA;
        String[] projection = {column};
        try {
            cursor = context.getContentResolver().query(uri, projection,
                    selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }

        return null;
    }

    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri
                .getAuthority());
    }

    private static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri
                .getAuthority());
    }

    private static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri
                .getAuthority());
    }

    private static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri
                .getAuthority());
    }
}
